<?php

namespace App\Http\Controllers\Admin;

use App\Admin as AdminModel;
use App\Events\LoginEvent;
use App\Http\Controllers\Controller;
use App\Http\Requests\AdminLogin as AdminLoginRequest;
use \Db;

class Login extends Controller
{
    public function __construct()
    {

    }

    public function index()
    {
        if (session()->has('admin')) {
            return redirect('admin/index/main');
        }
        return view('admin.login.login');
    }

    public function verify(AdminLoginRequest $adminLoginRequest)
    {
        try {
            $data = $adminLoginRequest->all();
            //验证登录信息
            $adminInfo = AdminModel::where('account', '=', $data['account'])
                ->where('is_enable', '=', 1)
                ->first();
            if (!$adminInfo) {
                return showError('请填写正确的账号！');
            }

            $result = password_verify($data['login_password'], $adminInfo['login_password']);
            if ($result === false) {
                return showError('请填写正确的登录密码！');
            }

            //记录登录ip 和 登录时间
            event(new LoginEvent($adminInfo));

            $adminInfo['login_time']  = date('Y-m-d H:i:s', time(0));
            $adminInfo['ip']          = $adminLoginRequest->getClientIp();
            $adminInfo['login_count'] = DB::table('login_log')->count();

            session(['admin' => $adminInfo]);

            return showSuccess('登陆成功！', ['url' => url('admin/index/main')]);
        } catch (\Exception $e) {
            return showError('登陆失败！');

        }
    }

    public function signOut()
    {
        session()->forget('admin');
        return showSuccess('退出成功', ['url' => url('admin/login')]);

    }
}
